<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */
namespace KernelModule\LogsModule\AclModule;

use Nette\Environment;
use Nette\Debug;
use Nette\Paginator;
use Nette\VisualPaginator;

use \KernelModule\BasePresenter;
use Albireo\DatePicker;

/**
 * Displays the Security logs
 *
 * @author     Pavel
 * @package    Kernel
 */
class DisplayPresenter extends BasePresenter {
    
    private $page;

    /** @var AclLogs */
    private $aclLogs;
    private $limitPerPage = 10;

    /**
     * @return AclLogs model
     */
    public function getAclLogs() {
        if ($this->aclLogs === NULL)
            $this->aclLogs = new AclLogs();
        return $this->aclLogs;
    }

    /**
     *
     * @param String $date String value of the minimal date we want to show.
     *          For example "2010-12-03".
     */
    public function renderDefault() {
        $this->showMenu();

        $dataSource = $this->getAclLogs()->getDataSource();
        $paginator = $this["paginator"]->getPaginator();

        if (isset($this->page)) {
            $paginator->setPage($this->page);
        }
        //$this->invalidateControl("paginator");

        $paginator->itemCount = $dataSource->getTotalCount();
        $dataSource->applyLimit($paginator->itemsPerPage, $paginator->offset);


        $logs = array();

        foreach($dataSource as $row) {
            if($row->acl_id == NULL) {
                $row->acl_id = _("N/A");
            }
            $timestamp = $row->time->getTimestamp();
            $timeStr = date("j.n.Y H:i:s", $timestamp);
            $row->time = $timeStr;
            $logs[] = $row;
        }

        $this->template->title = _("Security Logs");
        $this->template->logs = $logs;

        //if ($this->isAjax()) $this->invalidateControl("aclLogs");
    }

    protected function createComponentDatepickerForm() {
        $datePicker = new DatePicker();
        return $datePicker->getDatePicker($this);
    }

    public function datePickerSubmitted($form) {
        $values = $form->values;
        $date = $values['date'];

        $timestamp = strtotime($date) + 60 * 60 * 24;

        $paginator = $this["paginator"]->getPaginator();

        $countNewerThan = $this->getAclLogs()->countNewerThan($timestamp);

        $this->page = floor($countNewerThan / $paginator->itemsPerPage) + 1;

        $this->setView("default");
    }

    public function createComponentPaginator() {
        $visualPaginator = new VisualPaginator();
        $visualPaginator->paginator->setItemsPerPage($this->limitPerPage);
        return $visualPaginator;
    }
    
    
}